package com.example.permission.controller;

import com.example.permission.common.page.Page;
import com.example.permission.common.result.Result;
import com.example.permission.entity.dto.PasswordDTO;
import com.example.permission.entity.dto.SysUserDTO;
import com.example.permission.entity.dto.UserRoleDTO;
import com.example.permission.entity.dto.page.SysUserPageDTO;
import com.example.permission.entity.po.SysUser;
import com.example.permission.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户信息表
 *
 * @author xuwq
 * @date 2020-05-09 15:56:07
 */
@RestController
@Api(tags = "用户信息表")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("v1/user")
    @ApiOperation("新增")
    public Result<SysUser> add(@RequestBody @Valid SysUserDTO sysUserDTO) {
        return Result.success(this.sysUserService.insert(sysUserDTO));
    }

    @PutMapping("v1/user/{userId}")
    @ApiOperation("修改")
    public Result<SysUser> edit(@PathVariable("userId") Integer userId, @RequestBody @Valid SysUserDTO sysUserDTO) {
        sysUserDTO.setUserId(userId);
        return Result.success(this.sysUserService.update(sysUserDTO));
    }

    @DeleteMapping("v1/user/{userId}")
    @ApiOperation("删除")
    public Result<Boolean> deleteById(@PathVariable("userId") Integer userId) {
        return Result.success(this.sysUserService.deleteById(userId));
    }

    @GetMapping("v1/user/{userId}")
    @ApiOperation(value = "根据id查询数据")
    public Result<SysUser> queryById(@PathVariable("userId") Integer userId) {
        return Result.success(this.sysUserService.queryById(userId));
    }

    @PostMapping("v1/user/multi")
    @ApiOperation(value = "查询分页列表")
    public Result<Page<SysUser>> queryListByPage(@RequestBody @Valid SysUserPageDTO sysUserPageDTO) {
        return Result.success(this.sysUserService.queryListByPage(sysUserPageDTO));
    }

    @PatchMapping("v1/user/password/{userId}/reset")
    @ApiOperation(value = "重置密码")
    public Result resetPassword(@PathVariable("userId") Integer userId) {
        this.sysUserService.resetPassword(userId);
        return Result.success();
    }

    @PatchMapping("v1/user/password/{userId}/forget")
    @ApiOperation(value = "修改密码")
    public Result resetPassword(@PathVariable("userId") Integer userId, @RequestBody @Valid PasswordDTO passwordDTO) {
        return this.sysUserService.forgetPassword(userId, passwordDTO);
    }

    @PutMapping("v1/user/{userId}/role")
    @ApiOperation(value = "角色分配")
    public Result roleDistribution(@PathVariable("userId") Integer userId, @RequestBody @Valid UserRoleDTO userRoleDTO) {
        this.sysUserService.roleDistribution(userId, userRoleDTO.getRoleIds());
        return Result.success();
    }

}